package com.smsc.headend.connector.netty.initializer;

import cn.hutool.extra.spring.SpringUtil;
import com.smsc.headend.connector.netty.decoder.BytesInboundCounter;
import com.smsc.headend.connector.netty.decoder.DecodeProxy;
import com.smsc.headend.connector.netty.decoder.ansi.AnsiByteDecoder;
import com.smsc.headend.connector.netty.encoder.AnsiEncoder;
import com.smsc.headend.connector.netty.handler.AnsiPacketHandler;
import com.smsc.headend.connector.netty.handler.BytesOutboundCounter;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;

public class AnsiInitializer extends ChannelInitializer {
    @Override
    protected void initChannel(Channel channel) throws Exception {
        AnsiEncoder ansiEncoder = new AnsiEncoder();
        DecodeProxy decodeProxy = new DecodeProxy();
        BytesInboundCounter bytesInboundCounter = new BytesInboundCounter();
        BytesOutboundCounter bytesOutboundCounter = new BytesOutboundCounter();
        AnsiByteDecoder ansiDecoder = new AnsiByteDecoder();
        AnsiPacketHandler handler = new AnsiPacketHandler();
        AutowireCapableBeanFactory autowireCapableBeanFactory = SpringUtil.getApplicationContext().getAutowireCapableBeanFactory();
        autowireCapableBeanFactory.autowireBean(ansiEncoder);
        autowireCapableBeanFactory.autowireBean(bytesInboundCounter);
        autowireCapableBeanFactory.autowireBean(bytesOutboundCounter);
        autowireCapableBeanFactory.autowireBean(handler);
        ChannelPipeline p = channel.pipeline();
        p.addLast("encoder", ansiEncoder);
        p.addLast("proxyDecoder", decodeProxy);
        p.addLast("bytesInBoundCounter", bytesInboundCounter);
        p.addLast("bytesOutboundCounter", bytesOutboundCounter);
        p.addLast("decoder",  ansiDecoder);
        p.addLast(new IdleStateHandler(15, 15, 30), handler);
    }
}
